<template>
  <el-card>
    <!-- 表头 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="searchObj.username"
          size="small "
          placeholder="用户名"

        ></el-input>
      </el-form-item>

      <el-form-item style="margin: 0 20px">
        <el-button
          type="primary"
          @click="onSubmit"
          size="small"
          icon="el-icon-zoom-out"
          >查询</el-button
        >
        <el-button size="small " :disabled="!this.searchObj.username" @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>

    <div style="margin: 20px 0">
      <el-button type="primary" size="small" @click="dialogVisible=true">添加</el-button>
            <!-- <el-popconfirm  :title="`确定要删除吗？`" @confirm="deleteuserlist"> -->
      <el-button type="danger" slot="reference"   size="small "   @click="deleteuserlist">批量删除</el-button>
           <!-- </el-popconfirm> -->
    </div>
    <!-- 表格 -->
    <el-table :data="pagelist.items" border style="width: 100%"   
       @selection-change="handleSelectionChange"  >
          <el-table-column type="selection" width="55">
    </el-table-column>
      <el-table-column fixed  type="index" label="序号" width="80">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150"> </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="120">
      </el-table-column>
      <el-table-column prop="roleName" label="角色列表" width=""> </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="180">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="200"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template slot-scope="{row}">
          <el-button  title="分配角色" type="info" size="small" icon="el-icon-user-solid"  @click="Allocationsubject(row)"></el-button>
          <el-button type="primary" size="small"  title="修改用户" @click="alteruser(row)"  icon="el-icon-edit"></el-button>


      <el-popconfirm  :title="`确定要删除吗？`" @confirm="deleteuser(row)">
        <el-button type="danger" size="small" slot="reference" icon="el-icon-delete"  style="margin-left:12px"  ></el-button>
        </el-popconfirm>

  
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
    style="margin-top:15px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      
      :page-sizes="[5, 10, 20, 30]"
      :page-size="100"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total">
    </el-pagination>







<el-dialog 
  top='5vh'
  :title="ruleForm.id? '修改数据':'新增数据' "

  :visible.sync="dialogVisible"
  width="50%"
  :before-close="handleClose">

  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item  label="用户名" prop="username"  >
    <el-input v-model="ruleForm.username"  type="text"></el-input>
  </el-form-item>
  <el-form-item label="用户昵称" >
    <el-input v-model="ruleForm.nickName"  type="text"></el-input>
  </el-form-item>

  <el-form-item label="用户密码" prop="password"  v-if="!ruleForm.id">
    <el-input v-model="ruleForm.password"  type="password"></el-input>
  </el-form-item>
    <el-form-item>

    <el-button type="primary" @click="submitForm('ruleForm')" >确 定</el-button>
    <el-button  @click="resetForm('ruleForm')" >取 消</el-button>
     </el-form-item>
  </el-form>
 


</el-dialog>


<!-- 分配角色列表 -->
<!-- before-close   关闭前的回调，会暂停 Dialog 的关闭    unction(done)，done 用于关闭 Dialog -->
<!-- 是否显示 Dialog，支持  通过 .sync 修饰符可以修改父组件的值 -->
  <el-dialog title="设置角色" :visible.sync="dialogRoleVisible" :before-close="resetRoleData">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" 
          @change="handleCheckAllChange" 
          >全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button :loading="loading" type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </div>
    </el-dialog>








  </el-card>
</template>

<script>
//引入api
import userApi from '@/api/acl/user'
import { Message } from 'element-ui';
import { cloneDeep } from 'lodash'
export default {
  name: "User",

  data() {
    return {
      formInline: {
        user: "",
        region: "",
        },


        // 分页
       
        page:1,
        limit:5,
        total:0,
        searchObj: { // 收集搜索条件输入的对象
        username: ''
        },
         tempSearchObj: { // 包含请求搜索条件数据的对象
        username: ''
      },
        searname:'',
        pagelist:{},//获取的数据列表
        dialogVisible: false , //表格弹窗
    
        

      // 表单验证
      ruleForm: {
        username:'',
        nickName:'',
        password:'',

        },
        rules: {
          username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 5, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:[
             { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
          ]
        },
   
  multipleSelection:[], //选中的每一条数据的id


  //获取角色数据
    allRoles: [], // 所有角色列表
    userRoleIds: [], // 用户的角色ID的列表
    user: {}, // 当前要操作的user
    dialogRoleVisible: false, // 是否显示角色Dialog
    checkAll:false,//全选按钮
    isIndeterminate: false, // 是否是不确定的
     loading: false, // 是否正在提交请求中
  
    };
  },
//========查询========//
  methods: {
    onSubmit() {
      this.tempSearchObj =this.searchObj
        this.getpagelist()
    },

     /* 
    重置输入后搜索
    */
    resetSearch () {
      this.searchObj = {
        username: ''
      }
      this.tempSearchObj = {
        username: ''
      }
      this.getpagelist()
    },

//=========分页============//
    handleSizeChange(val) {
        this.limit=val
           this.getpagelist()
    },
    handleCurrentChange(val) {
       this.page=val
          this.getpagelist()
      },
//============================//


//======获取用户信息=====//
  async getpagelist(){
    try {
      const result=await userApi.getPageList(this.page,this.limit,this.tempSearchObj)
            // console.log(result)
     
        this.pagelist=result.data
        this.total=result.data.total
        console.log(pagelist)
      
      } catch (error) {
        console.log('错误',error)
        }    

  },

//===========点击添加=========//
 handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },

//==========添加================//
// async addsublist(){
  
//     const result=await userApi.add(this.ruleForm)
//       console.log(result)
//     if(result.code===20000){
//       Message.error("添加成功")
//           this.getpagelist()
//     }else{
//       Message.error("添加失败请重试")
//     }
// },


//=======表单验证====修改=====//

  //修改数据回显
  alteruser(row){
    this.dialogVisible=true,
    this.isshow=false,
    this.ruleForm= cloneDeep(row) 
  },




  //取消的回调
        resetForm(formName) {
          this.ruleForm={}
          this.dialogVisible=false,
          this.$refs[formName].resetFields();

        },


  //点击确认
  submitForm(formName) {
  
  this.$refs[formName].validate(async(valid) => {
    if (valid) {
        const {id}=this.ruleForm
    if(id){
      await userApi.update(this.ruleForm)
   Message.error("修改成功")
       this.getpagelist()
       this.resetForm()

      }else{
    await userApi.add(this.ruleForm)
     Message.error("添加成功")
         this.getpagelist()
         this.resetForm()  //主要调用其中的方法
  }
        
          }else{
             Message.error('添加失败,请重试')
            return false;
          }
        });
      },



      

//=========删除===============//
async deleteuser(row){
  console.log(row)
const result= await userApi.removeById(row.id)
  Message.error('删除成功')
if(result.code===20000){
    this.getpagelist()
}else{
  Message.error('删除失败')
}
},  






//=======批量删除===========//
    // 给我点击的数据放到数组里
    handleSelectionChange(val){
      
      this.multipleSelection = val
    },


//批量删除点击事件
 deleteuserlist(){
  console.log("111111")
    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'}).then( async()=>{
            const sid=this.multipleSelection.map(item=>item.id)
             console.log(sid)
            await userApi.removeUsers(sid)
          this.getpagelist()
                this.$message({
            type: 'success',
            message: '删除成功!'
          });

          }).catch(()=>{

              this.$message({
            type: 'info',
            message: '已取消删除'
          });          
          })

},

//=========获取角色===========//
//取消的回调
resetRoleData(){
        this.dialogRoleVisible = false //关闭对话框
          this.allRoles=[],//清空数组列表
          this.userRoleIds=[],//清空id
          this.isIndeterminate = false,
          this.checkAll = false
},

//分类角色按钮
Allocationsubject(row){
  console.log(row)  
    this.dialogRoleVisible=true  // 对话框的展示
    this.user=row  //将获取到的对象赋值给新的对象
    this.getRoles() //获取角色列表
 
    
},

//获取用户角色列表  
async getRoles(){
  const result=await userApi.getRoles(this.user.id)
  console.log(result)
  const {allRolesList,assignRoles}=result.data  //获取角色列表
  // 获取到重新赋值
  this.allRoles=allRolesList
  this.userRoleIds=assignRoles.map(item=>item.id)
},

//全选与全不选
handleCheckAllChange(e){
  console.log(e)  //true /fasle
   // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
   this.userRoleIds=e? this.allRoles.map(item=>item.id):[]
 // 如果当前不是全选也不全不选时, 指定为false
 console.log(this.userRoleIds)
      this.isIndeterminate = false  
},

//点击单个选项框
handleCheckedChange(e){
    const {userRoleIds, allRoles} = this
    this.checkAll=userRoleIds.length===allRoles.length && allRoles.length>0
    this.isIndeterminate=userRoleIds.length>0 && userRoleIds.length<allRoles.length
},


//保存角色配置 组装角色
async assignRole(){
    const userId=this.user.id
    const rouleIds=this.userRoleIds.join(',')
    console.log('保存',userId,rouleIds)
    this.loading = true
    const result =await userApi.assignRoles(userId,rouleIds)
    this.loading = false
    this.resetRoleData()
        this.getpagelist()
}



  },

  mounted() {
     this.getpagelist()
  },
};



</script>

<style scoped></style>
